// Globals
float4x4 World;
float4x4 View;
float4x4 Projection;
float4x4 InvertViewProjection;

float3 lightPosition;
float3 color;
float lightRadius;
float lightIntensity;

texture normaltex;
texture depthtex;

sampler NormalTex
{
	Texture = <normaltex>;
	MinFilter = POINT;
	MagFilter = POINT;
	MipFilter = POINT;
	AddressU = CLAMP;
	AddressV = CLAMP;
};

sampler DepthTex
{
	Texture = <depthtex>;
	MinFilter = POINT;
	MagFilter = POINT;
	MipFilter = POINT;
	AddressU = CLAMP;
	AddressV = CLAMP;
};

// Define a vertex shader output structure;
struct OutputVS
{
    float4 pos: POSITION0;
    float4 screenPos: TEXCOORD0;
};

// Vertex shader -------------------------------------------------------------------------------------
OutputVS TransformVS( float3 position:POSITION0 )
{
	// output structure
	OutputVS outVS;
	
	float4 worldPos = mul( float4( position, 1.0f ), World );
	float4 viewPos = mul( worldPos, View );
	
	outVS.pos = mul( viewPos, Projection );
	outVS.screenPos = outVS.pos;
	
    return outVS;
}


// Pixel Shader ---------------------------------------------------------------------------
float4 TransformPS( OutputVS inVS ): COLOR0
{
	inVS.screenPos.xy /= inVS.screenPos.w;
	float2 texCoord = 0.5f * ( float2( inVS.screenPos.x, -inVS.screenPos.y ) + 1.0f );
	
	float4 normal = tex2D( NormalTex, texCoord );
	float3 pixNorm = ( normal.xyz * 2.0f ) - 1.0f;
	
	float depth = tex2D( DepthTex, texCoord ).r;
	
	float4 pos;
	pos.xy = inVS.screenPos.xy;
	pos.z = depth;
	pos.w = 1.0f;
	
	pos = mul( pos, InvertViewProjection );
	pos /= pos.w;
		
	float3 lightVec = lightPosition - pos.xyz;
	
	float3 attenuation = saturate( 1.0f - length( lightVec / lightRadius ) );
	lightVec = normalize( lightVec );
	
	float LightToNorm = max( 0, dot( lightVec, normal ) );
	float3 diffuse = LightToNorm * color;
	
	
	float3 normalLight = max( 0, dot( normal, lightVec ) );
	
	return ( float4( attenuation * lightIntensity, 1.0f ) * float4( diffuse.rgb, 1.0f ) );
}

// ----------------------------------------------------------------------------------------
technique BasicCCW
{
    pass P0
    {
        vertexShader = compile vs_2_0 TransformVS();
        pixelShader  = compile ps_2_0 TransformPS();
      
		ShadeMode = Flat;
        //FillMode = WIREFRAME;
        
        CullMode = CW;
    }
}

technique BasicCW
{
    pass P0
    {
        vertexShader = compile vs_2_0 TransformVS();
        pixelShader  = compile ps_2_0 TransformPS();
      
		ShadeMode = Flat;
        //FillMode = WIREFRAME;
        
        CullMode = CW;
    }
}